import platform
from PyQt5.QtWidgets import QSystemTrayIcon, QMenu, QAction
from PyQt5.QtGui import QIcon, QCursor

def create_qt_tray_icon(app):
    """为PyQt5创建系统托盘图标"""
    tray = QSystemTrayIcon(QIcon("voice_assistant/assets/icons/microphone.png"))
    
    def open_m3u8_download():
        """打开 M3U8 下载页面"""
        try:
            import sys
            import os
            from PyQt5.QtCore import QTimer
            
            # 添加项目根目录到Python路径
            root_dir = os.path.abspath(os.path.join(os.path.dirname(__file__), '..', '..'))
            if root_dir not in sys.path:
                sys.path.insert(0, root_dir)
            # 导入m3u8_pro模块
            from m3u8_pro.main import main as m3u8_main
            
            # 使用 QTimer.singleShot 在主事件循环中执行
            # 确保不会阻塞主线程或导致应用程序退出
            QTimer.singleShot(0, m3u8_main)
        except Exception as e:
            print(f"打开M3U8下载失败: {str(e)}")
    
    def open_image_download():
        """打开图片下载页面"""
        try:
            import sys
            import os
            from PyQt5.QtCore import QTimer
            
            # 添加项目根目录到Python路径
            root_dir = os.path.abspath(os.path.join(os.path.dirname(__file__), '..', '..'))
            if root_dir not in sys.path:
                sys.path.insert(0, root_dir)
            
            # 导入image_pro模块替代旧的image模块
            from image_pro.main import main as image_pro_main
            
            # 使用 QTimer.singleShot 在主事件循环中执行
            # 确保不会阻塞主线程或导致应用程序退出
            QTimer.singleShot(0, image_pro_main)
        except Exception as e:
            print(f"打开图片下载失败: {str(e)}")
    
    # 创建托盘菜单 - 确保有父窗口
    from PyQt5.QtWidgets import QWidget
    parent_widget = QWidget()
    parent_widget.setWindowTitle("TrayIconParent")
    menu = QMenu(parent_widget)
    
    # 保存父窗口引用，防止被垃圾回收
    tray.parent_widget = parent_widget
    
    # 添加菜单项
    m3u8_action = QAction("M3U8 下载", parent_widget)
    m3u8_action.triggered.connect(open_m3u8_download)
    
    image_action = QAction("图片下载Pro", parent_widget)
    image_action.triggered.connect(open_image_download)
    
    settings_action = QAction("设置", parent_widget)
    settings_action.triggered.connect(lambda: print("打开设置..."))
    
    quit_action = QAction("退出", parent_widget)
    quit_action.triggered.connect(app.shutdown)
    
    menu.addAction(m3u8_action)
    menu.addAction(image_action)
    menu.addAction(settings_action)
    menu.addSeparator()
    menu.addAction(quit_action)
    
    # 添加菜单到托盘
    tray.setContextMenu(menu)
    
    # 修复在Windows系统上的右键菜单问题
    if platform.system() == "Windows":
        # 添加左键点击处理，使左键点击也显示菜单
        def on_tray_activated(reason):
            if reason == QSystemTrayIcon.Trigger:  # 左键点击
                menu.exec_(QCursor.pos())
                
        tray.activated.connect(on_tray_activated)
    
    # 托盘提示
    tray.setToolTip("语音助手")
    
    return tray